package dao

import (
	"ams_client/global"
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"lib/db"
	"lib/structs/ams"
	"lib/structs/tables"
)

var DB *gorm.DB

func InitDB() (err error) {
	DB, err = db.GetDB(global.Conf.DB.Supper, global.Conf.DB.ShowSqlLog, global.Conf.DB.Source, global.Conf.AppFolder)
	if err != nil {
		err = fmt.Errorf("连接数据库失败：%v", err)
		return
	}
	autoMigrate()
	err = LoadCache()
	if err != nil {
		err = fmt.Errorf("加载数据库缓存失败：%v", err)
	}
	return
}

func autoMigrate() {
	type vector[T any] []T
	var li = vector[interface{}]{
		&tables.ClientAmsLog{},
		&tables.ClientAmsPolicy{},
		&tables.ClientAmsConfig{},
	}
	for _, item := range li {
		if !DB.Migrator().HasTable(item) {
			err := DB.AutoMigrate(item)
			if err != nil {
				logrus.Errorf("初始化数据库表结构异常: %v", err)
			}
		}
	}
	//initClientAmsConfig()
}

func initClientAmsConfig() {
	li := []tables.ClientAmsConfig{
		{ams.ConfigKeyForLog, "debug"},
		{ams.ConfigKeyForAmsCode, ""},
		{ams.ConfigKeyForUniqueType, ""},
		{ams.ConfigKeyForHandsUp, ""},
		{ams.ConfigKeyForGuarder, ""},
		{ams.ConfigKeyForFileServer, ""},
	}
	var num int64
	err := DB.Model(&tables.ClientAmsConfig{}).Count(&num).Error
	if err != nil {
		logrus.Errorf("initClientAmsConfig err: %v", err)
		return
	}
	if num == 0 {
		err = DB.CreateInBatches(li, len(li)).Error
		if err != nil {
			logrus.Errorf("initClientAmsConfig err: %v", err)
			return
		}
	}
}
